package cn.inst.login.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.inst.common.SecurityUntils;
import cn.inst.user.domain.User;
import cn.inst.user.service.CheckUserServiceImp;

@Controller
@RequestMapping("login")
public class LoginController {
	@Autowired
	private CheckUserServiceImp checkUser;

	@RequestMapping("/index")
	public String login() {
		System.out.println("进入登录");
		return "login";

	}
	
	@ResponseBody
	@RequestMapping("/check")
	public String logincheck(HttpServletRequest request,User testUser) throws ServletException, IOException {
		System.out.println("进入登录校验");
		
		UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(testUser.getUsername(),testUser.getPassword());
		try {
			Subject subject=SecurityUtils.getSubject();
			subject.login(usernamePasswordToken);
			//登录成功,由本地线程获取user对对象,把user放到session域
			User user = (User) subject.getPrincipal();
			request.getSession().setAttribute("userinfo", user);
			//返回登录成功
			return "login_succ";
		} catch (Exception e) {
			//抛出异常,登录失败
			e.printStackTrace();
			return "login_false";
		}
	
		
		//1、查询数据库中是否有这个user
//		User user = checkUser.checkUser(testUser);
//		if(user!=null){
//			//2、有则把user放到session，然后跳转到HOME
//			request.getSession().setAttribute("userinfo", user);
//			return "login_succ";
//		}else{
//			//3、无则重新回登录界面
//			return "login_false";
//		}
	}
	

}
